<template>
  <div class="home-container">
    <div class="home-header">
    <van-dropdown-menu  active-color="#1989fa" direction="down" >
        <van-dropdown-item @change="changeOrg" :title="orgname" v-model="token" :options="organizations" >
        </van-dropdown-item>
      </van-dropdown-menu>

      <div class="home-content">
        <van-image class="home-avatar" fit="cover" :round="true" :src="avatarSrc" />
        <div class="home-name" @click="toPage('person')">{{name}} <van-icon name="arrow" size="24px" /></div>
      </div>
    </div>
    <van-cell title="安全承诺书" :border="false">
        <van-loading v-if="safeDealLoading" size="16px" type="spinner"></van-loading>
        <span v-else slot="right-icon">
          <span  @click="toSignProposal(1)" v-if="!proposalContract" style="color:#1989fa;">去签署</span>
          <span  v-else-if="proposalContract && (proposalContract.FlowStatus === 'ALL')" style="color:#797979;">已签署</span>
          <span v-else @click="toSignProposal(2)" style="color:#797979;">签署截止时间：{{proposalContract.DeadLine|timeFilter}} >></span>
        </span>
    </van-cell >
    <div class="home-cell">
      <div class="home-cell-title" @click="toPage('contracts')">我的合同 <van-icon name="arrow" size="20px" /></div>
      <div class="home-cell-con">
        <div class="home-cell-half" @click="toPage('contracts', 'WAITSIGN')">
          <van-badge :content="contractWaitsignCount" v-if="contractWaitsignCount">
            <div class="home-waitsign"></div>
          </van-badge>
          <div class="home-waitsign" v-else></div>
          <div class="home-cell-text">待签署</div>
        </div>
        <div class="home-cell-half" @click="toPage('contracts', 'SIGNED')">
          <div class="home-signed"></div>
          <div class="home-cell-text">已签署</div>
        </div>
      </div>
    </div>
    <div class="home-cell" @click="toPage('sendRecord')">
      <div class="home-cell-title" >我的工作 <van-icon name="arrow" size="20px"  v-if="workInfo"/></div>
      <div v-if="workLoading" class="home-loading" size="36"  ><van-loading /></div>
      <div v-if="workInfo && !workLoading">
        <div class="home-cell-word">
          {{workInfo.tenantName}}
          <van-tag mark size="medium" :type="workInfo.status" style="margin-left:5px;">{{workInfo.status | statusText}}</van-tag>
        </div>
        <div class="home-cell-word gray mini">服务时间：{{workInfo.startTime|timeFilter}} ~ {{workInfo.endTime|timeFilter}}</div>
      </div>
      <van-empty v-if="!workInfo && !workLoading" description="暂无工作记录" />
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex';
import { Toast } from 'vant';

import { getH5ContractList, createSingleContract, createH5SignUrl } from '@common/api/contract';
import { getHomeSendList } from '@common/api/send';
import { formatTime } from '@common/utils/time';
import { getOrganizations, getInfo  } from '@common/api/user';
import { getProposalContracts  } from '@common/api/worker';
import moment from 'moment';

import avatarPng from '../assets/male.jpg';
import avatarPng2 from '../assets/female.jpg';

export default {
  name: 'home',
  filters: {
    timeFilter(time) {
      if (time) return formatTime(time, { format: 'YYYY-MM-DD' });
      return '--';
    },
    statusText(status) {
      if (status === 'success') {
        return '服务中';
      } if (status === 'over') {
        return '已结束';
      }
      return '未开始';
    },
  },
  data() {
    return {
      contractWaitsignCount: 0,
      workInfo: null,
      userInfo: {},
      workLoading: true,
      safeDealLoading: true, // 安全承诺书loading
      organizations: [],
      loading: false,
      proposalContract: null,
    };
  },
  computed: {
    ...mapGetters(['name', 'orgname', 'token', 'gender']),
    hasMutipleOrg() {
      return this.organizations?.length > 1;
    },
    avatarSrc() {
      return this.gender === 'FEMALE' ? avatarPng2 : avatarPng;
    },
  },
  created() {
    this.getProposalDeal();
    this.getOrganizationList();
    this.getContracts();
    this.getSendRecords();
  },
  mounted() {
    getInfo();
  },
  methods: {
    // 合同
    toPage(pathurl, params) {
      if (pathurl === 'sendRecord' && !this.workInfo) { // 没有工作记录时，不需要跳转
        return;
      }
      this.$router.push({
        path: `/${pathurl}`,
        query: params ? { contractStatus: params } : '',
      });
    },

    async getContracts() {
      try {
        const res = await getH5ContractList({
          limit: 10,
          offset: 0,
          contractType: 2, // 劳动合同
          status: 'WAITSIGN',
        });
        this.contractWaitsignCount = res?.data?.totalCount || 0;
      } catch (error) {
        this.contractWaitsignCount = 0;
        console.log('error=====', error);
      }
    },
    async getSendRecords() {
      try {
        const res = await getHomeSendList({ workerId: this.token });
        const now = new Date();
        this.workInfo = res?.data?.list?.[0] || null;
        if (this.workInfo) {
          if (moment(this.workInfo.startTime) - moment(now) > 0) { // 未开始
            this.workInfo.status = 'primary';
          } else if (moment(this.workInfo.endTime) - moment(now) > 0) { // 服务中
            this.workInfo.status = 'success';
          } else { // 已结束
            this.workInfo.status = 'over';
          }
        }
        this.workLoading = false;
      } catch (error) {
        this.workLoading = false;
      }
    },
    async getOrganizationList() {
      try {
        const { data } = await getOrganizations();
        this.organizations = data.organizations.map(v => ({
          ...v,
          text: v.organizationName,
          value: v.workerId,
        }));
      } catch (error) {
        this.organizations = [];
      }
    },
    // 切换用工单位
    async changeOrg(value) {
      this.loading = true;
      this.workLoading = true;
      this.safeDealLoading = true;
      await this.$store
        .dispatch('user/switchOrg', value);
      await  this.$store.dispatch('user/getInfo');
      await Promise.all([this.getContracts(), this.getSendRecords()], this.getProposalDeal());
      this.loading = false;
    },
    async toSignProposal(type) { // type: 1 需要生成合同，2 不需要生成合同，直接创建签署链接
      Toast.loading({
        forbidClick: true,
      });
      let res = null;
      try {
        if (type === 1) {
          res = await createSingleContract({
            signType: 'singleC',
          });
          if (res?.data?.SignUrl) {
            window.location.href = res?.data?.SignUrl;
          } else {
            Toast.fail(res.message || '签署失败，请稍后重试');
          }
        } else {
          res = await createH5SignUrl({ flowId: this.proposalContract.FlowId });
          // console.log(res);
          const flowUrlInfos = res.data?.FlowApproverUrlInfos;
          const urlInfo = flowUrlInfos[0];
          if (urlInfo) {
            window.location.href = (urlInfo.SignUrl);
          }
        // });
        }
        Toast.clear();
      } catch (error) {
        Toast.fail(error.message || '签署失败，请稍后重试');
      }
    },
    async getProposalDeal() {
      const res = await getProposalContracts();
      this.safeDealLoading = false;
      if (res?.data?.contract) {
        this.proposalContract = res.data.contract;
      } else {
        this.proposalContract = null;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.home-container {
  position: relative;
  width: 100%;
  height: 100vh;
  background: #f5f5f5;
  .home-header {
    position: relative;
    width: 100%;
    height: 380px;
    color: #fff;
    background: #334154;
    .home-content {
      position: relative;
      margin-top: 50px;
      .home-avatar {
        position: absolute;
        top: 0px;
        left: 30px;
        width: 160px;
        height: 160px;
        background: #eee;
        border-radius: 50%;
      }
      .home-name, .home-company {
        padding-left: 220px;
        font-size: 28px;
      }
      .home-name {
        font-size: 40px;
        font-weight: bolder;
        position: relative;
        top:40px;
        .van-icon-arrow {
          position: absolute;
          right: 30px;
          top: 4px;
          display: inline-block;
          color: #fff;
        }
      }
      .home-company {
        margin-top: 70px;
      }
    }
  }
  .home-cell {
    position: relative;
    margin: 20px;
    padding: 30px;
    font-size: 28px;
    background: #fff;
    border-radius: 10px;
    .home-cell-title {
      font-size: 28px;
      font-weight: bold;
      margin-bottom: 20px;
      .van-icon-arrow {
        position: absolute;
        right: 20px;
        top: 26px;
        display: inline-block;
        color: #666;
      }
    }
    .home-cell-con {
      display: flex;
      .home-cell-half {
        flex: 1;
        text-align: center;
        padding: 20px 0;
        .home-waitsign {
          display: inline-block;
          width: 80px;
          height: 80px;
          background: url('../assets/edit.png') no-repeat;
          background-size: 80px 80px;
        }
        .home-signed {
          display: inline-block;
          width: 80px;
          height: 80px;
          background: url('../assets/sign.png') no-repeat;
          background-size: 80px 80px;
        }
        .home-cell-text {
          margin-top: 20px;
        }
      }
    }
    .home-cell-word {
      font-size: 28px;
      line-height: 50px;
    }
    .gray {
      color: #666;
    }
    .mini {
      font-size: 24px;
    }
  }
  .home-loading {
    position: relative;
    text-align: center;
    padding: 30px 0;
  }
}

</style>
<style>
.home-header .van-dropdown-menu__bar {
    background-color: #334154 !important;
    color:#fff;
    box-shadow: none;
  }
  .home-header .van-dropdown-menu__title{
    color: #fff;
    font-size: 32px;
  }
</style>
